import 'dart:io';

// 3. تخزين البيانات: استخدام قائمة لتخزين الدخل والمصروفات
// كل إدخال يتم تخزينه كـ Map يحتوي على 'description' (String) و 'amount' (double).
List<Map<String, dynamic>> incomeList = [];
List<Map<String, dynamic>> expenseList = [];

void main() {
  print("Welcome to the Budget Management Application!");

  // 5. استخدام حلقة (loop) للسماح بالتفاعل المستمر
  bool isRunning = true;
  while (isRunning) {
    displayMenu();
    String? choice = stdin.readLineSync();

    if (choice == null) {
      continue;
    }

    // 5. استخدام if/else أو switch للتعامل مع خيارات القائمة
    switch (choice) {
      case '1':
        addEntry(true); // إضافة دخل
        break;
      case '2':
        addEntry(false); // إضافة مصروف
        break;
      case '3':
        viewSummary(); // عرض الملخص
        break;
      case '4':
        isRunning = false;
        print("Exiting the application. Goodbye!");
        break;
      default:
        print("Invalid choice. Please enter a number between 1 and 4.");
    }
    print("---");
  }
}

void displayMenu() {
  print("\nPlease choose an option:");
  print("1. Add income");
  print("2. Add expense");
  print("3. View summary");
  print("4. Exit");
  stdout.write("Enter your choice: ");
}

// دالة موحدة لإضافة إدخالات الدخل والمصروفات
void addEntry(bool isIncome) {
  String type = isIncome ? "income" : "expense";
  
  // 2. طلب الوصف
  stdout.write("Enter $type description: ");
  String? description = stdin.readLineSync();
  if (description == null || description.trim().isEmpty) {
    print("Description cannot be empty.");
    return;
  }

  // 2. طلب المبلغ و 4. التحقق من صحة المدخلات
  stdout.write("Enter $type amount: ");
  String? amountInput = stdin.readLineSync();

  double? amount = double.tryParse(amountInput ?? '');

  // 4. التحقق من صحة المدخلات: التأكد من أنه رقم موجب
  if (amount == null || amount <= 0) {
    print("Invalid amount. Please enter a positive numeric value.");
    return;
  }

  // إضافة الإدخال إلى القائمة المناسبة
  Map<String, dynamic> entry = {
    'description': description.trim(),
    'amount': amount,
  };

  if (isIncome) {
    incomeList.add(entry);
    print("Income added! (${entry['description']}: \$${entry['amount'].toStringAsFixed(2)})");
  } else {
    expenseList.add(entry);
    print("Expense added! (${entry['description']}: \$${entry['amount'].toStringAsFixed(2)})");
  }
}

void viewSummary() {
  // 7. العمليات الحسابية: حساب إجمالي الدخل
  double totalIncome = incomeList.fold(0.0, (sum, entry) => sum + entry['amount']);
  
  // 7. العمليات الحسابية: حساب إجمالي المصروفات
  double totalExpenses = expenseList.fold(0.0, (sum, entry) => sum + entry['amount']);

  // 7. العمليات الحسابية: حساب صافي الربح أو الخسارة
  double netProfit = totalIncome - totalExpenses;

  print("\nSummary:");
  
  // 6. استخدام التضمين النصي (String Interpolation) لعرض المبالغ
  print("Total Income: \$${totalIncome.toStringAsFixed(2)}");
  print("Total Expenses: \$${totalExpenses.toStringAsFixed(2)}");

  // 2. عرض صافي الربح أو الخسارة
  if (netProfit > 0) {
    print("Net Profit: \$${netProfit.toStringAsFixed(2)}");
  } else if (netProfit < 0) {
    // عرض صافي الخسارة كقيمة موجبة
    print("Net Loss: \$${(netProfit * -1).toStringAsFixed(2)}");
  } else {
    print("Net Result: \$0.00 (Break-even)");
  }

  // 8. التمرين الإضافي: حساب الضريبة (Tax Calculation)
  // 8. استخدام المشغل الثلاثي (Ternary Operator) لحساب الضريبة فقط في حال الربح
  double taxRate = 0.15; // 15%
  double taxToBePaid = netProfit > 0 ? netProfit * taxRate : 0.0;

  if (taxToBePaid > 0) {
    print("Tax to be paid (15% of Net Profit): \$${taxToBePaid.toStringAsFixed(2)}");
  }
}
